﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace RemoteProgramUpdate
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {

        }

        private async Task DownLoadFile(string filepath, string savepath)
        {
            Text = "下载开始";
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(filepath);

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            Stream stream = response.GetResponseStream();
            FileStream fileStream = new FileStream(textBox_SavePath.Text, FileMode.Create);

            progressBar.Maximum = (int)response.ContentLength;
            //Debug.WriteLine($"文件大小为【{response.ContentLength}】个字节");
            progressBar.Value = 0;

            byte[] buffer = new byte[1024*1024*20];
            int size = await stream.ReadAsync(buffer, 0, buffer.Length);
            while (size > 0)
            {
                //Debug.WriteLine($"本次下载字节数【{size}】");
                progressBar.Value += size;
                Text = $"下载字节数【{progressBar.Value}】";
                fileStream.Write(buffer, 0, size);
                size =await stream.ReadAsync(buffer, 0, buffer.Length);
            }

            stream.Close();
            fileStream.Close();


            Text = "下载完毕";
            //Debug.WriteLine("下载完毕");
        }

        private void label_SavePath_Click(object sender, EventArgs e)
        {
            folderBrowserDialog.ShowDialog();
            if (folderBrowserDialog.SelectedPath?.Length > 0)
            {
                textBox_SavePath.Text = folderBrowserDialog.SelectedPath+"\\1.mp4";
            }
        }

        private async void button_Start_Click(object sender, EventArgs e)
        {

            string filepath = textBox_FilePath.Text.Trim();
            if (filepath.Length == 0)
            {
                return;
            }

            string savepath = textBox_SavePath.Text.Trim();
            if (savepath.Length == 0)
            {
                return;
            }

            try
            {
                await DownLoadFile(filepath, savepath);
                //MessageBox.Show("保存完毕");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}
